<template>
  <v-card flat height="660" class="py-6 px-5">
    <v-form ref="form">
      <v-row no-gutter class="ma-0 mb-4">
        <v-col cols="6" class="pa-0">
          <v-row no-gutters>
            <v-col cols="4" class="text-left">Project Name</v-col>
            <v-col cols="5" class="text-left">
              <v-text-field
                v-model="propSettingInfo.projectName"
                v-validate="'required'"
                name="Project Name"
                placeholder="Enter Project Name"
                class="white-input"
                dense
                hide-details
                solo
              ></v-text-field>
              <span class="vee-validate-error">
                {{ errors.first("Project Name") }}
              </span>
            </v-col>
          </v-row>
        </v-col>
        <v-col cols="6" class="pa-0">
          <v-row no-gutters>
            <v-col cols="4" class="text-left">Priority</v-col>
            <v-col cols="8" class="text-left">
              <v-card width="37.5%" flat>
                <v-select
                  v-model="propSettingInfo.priority"
                  :items="priorityItems"
                  v-validate="'required'"
                  name="Priority"
                  class="white-input"
                  dense
                  hide-details
                  solo
                ></v-select>
              </v-card>
              <span class="vee-validate-error">
                {{ errors.first("Priority") }}
              </span>
            </v-col>
          </v-row>
        </v-col>
      </v-row>
      <v-row no-gutter class="ma-0 mb-4">
        <v-col cols="6" class="pa-0">
          <v-row no-gutters>
            <v-col cols="4" class="text-left">Project Type</v-col>
            <v-col cols="5" class="text-left">
              <v-text-field
                v-model="propSettingInfo.projectType"
                v-validate="'required'"
                name="Project Type"
                class="white-input"
                dense
                hide-details
                solo
              ></v-text-field>
              <span class="vee-validate-error">
                {{ errors.first("Project Type") }}
              </span>
            </v-col>
          </v-row>
        </v-col>
        <v-col cols="6" class="pa-0">
          <v-row no-gutters>
            <v-col cols="4" class="text-left">Project Location</v-col>
            <v-col cols="5" class="text-left">
              <v-text-field
                v-model="propSettingInfo.projectLocation"
                v-validate="'required'"
                name="Project Location"
                class="white-input"
                dense
                hide-details
                solo
              ></v-text-field>
              <span class="vee-validate-error">
                {{ errors.first("Project Location") }}
              </span>
            </v-col>
          </v-row>
        </v-col>
      </v-row>
      <v-row no-gutters class="align-start">
        <v-col cols="2" class="text-left pa-0">Project Description </v-col>
        <v-col cols="10">
          <v-textarea
            v-model="propSettingInfo.projectDescription"
            v-validate="'required'"
            name="Project Description"
            class="white-input"
            rows="3"
            hide-details
            no-resize
            solo
          ></v-textarea>
          <span class="vee-validate-error">
            {{ errors.first("Project Description") }}
          </span>
        </v-col>
      </v-row>
      <v-data-table
        disable-sort
        :headers="headers"
        :items="propSettingInfo.items"
        item-key="department"
        show-select
        class="elevation-0 form-info mt-6"
        hide-default-footer
      >
        <template #[`header.data-table-select`]>
          <div class="d-flex align-items">
            <v-btn
              @click="openSelectUser"
              class="rounded-pill"
              elevation="0"
              color="#79839B"
              width="20px"
              height="20px"
              fab
            >
              <v-icon color="#fff" size="16"> mdi-plus-thick </v-icon>
            </v-btn>
          </div>
        </template>
        <template #item="slotData">
          <tr>
            <td></td>
            <td>
              {{ slotData.item.department }}
            </td>
            <td>
              {{ slotData.item.userName }}
            </td>
            <td>
              <v-icon
                v-if="isAll(slotData.item)"
                @click="toggleAllRight(slotData.item)"
                color="#EB9B31"
                size="16"
              >
                mdi-check
              </v-icon>
              <v-icon v-else @click="toggleAllRight(slotData.item)" size="16">
                mdi-close
              </v-icon>
            </td>
            <td v-for="head in rightHeaders" :key="head.value">
              <v-icon
                v-if="slotData.item.right.includes(head.value)"
                @click="toggleRight(slotData.item, head.value)"
                color="#EB9B31"
                size="16"
              >
                mdi-check
              </v-icon>
              <v-icon
                v-else
                @click="toggleRight(slotData.item, head.value)"
                size="16"
              >
                mdi-close
              </v-icon>
            </td>
            <td>
              <div class="action d-flex">
                <v-tooltip bottom>
                  <template v-slot:activator="{ on }">
                    <v-btn
                      @click="openDelete(slotData.item)"
                      v-on="on"
                      class="pa-0 rounded-pill"
                      icon
                      depressed
                    >
                      <v-icon size="18" color="#79839B"> mdi-delete </v-icon>
                    </v-btn>
                  </template>
                  Delete Item
                </v-tooltip>
              </div>
            </td>
          </tr>
        </template>
      </v-data-table>
    </v-form>
    <Dialog
      @submit="save"
      v-model="showDialog"
      :title="dialogTitle"
      :show-save="step !== 2"
      :width="dialogWidth"
    >
      <template>
        <User v-if="step === 1" :selected.sync="checkedItems"></User>
        <Delete
          v-else-if="step === 2"
          @delete="save"
          title="Are you sure to delete this item?"
        ></Delete>
      </template>
    </Dialog>
  </v-card>
</template>
<script lang="ts">
import { Vue, Component } from "vue-property-decorator";
import { ISetting, ISettingItem, IUserItem } from "@/components/Customer/index";
import Dialog from "@/components/Maintenance/Dialog/Dialog.vue";
import Delete from "@/components/Customer/Dialog/Delete/Delete.vue";
import User from "@/components/Customer/Dialog/User/User.vue";
@Component({
  components: {
    Dialog,
    Delete,
    User,
  },
  props: {
    settingInfo: {
      type: Object,
      default: () => ({}),
    },
  },
})
export default class Setting extends Vue {
  get propSettingInfo(): ISetting {
    return this.$props.settingInfo;
  }

  priorityItems = ["Low", "Middle", "High"];

  checkedItems: IUserItem[] = [];
  // 1.AddItem 2.DeleteItem
  step = -1;
  // Dialog
  dialogTitle = "";
  showDialog = false;
  get dialogWidth() {
    if (this.step === 1) {
      return "1152";
    } else {
      return "480";
    }
  }
  openDialog() {
    this.showDialog = true;
  }
  closeDialog() {
    this.showDialog = false;
  }
  // table
  selectedItem: ISettingItem | null = null;
  headers = [
    { text: "Department", value: "department" },
    { text: "User Name", value: "userName" },
    { text: "All", value: "all" },
    { text: "Project Manager", value: "projectManager" },
    { text: "Read", value: "read" },
    { text: "Write", value: "write" },
    { text: "Delete", value: "delete" },
    { text: "Print", value: "print" },
    { text: "Export", value: "export" },
    { text: "Chat", value: "chat" },
    { text: "Library", value: "library" },
    { text: "Upload", value: "upload" },
    { text: "Delete Document", value: "deleteDocument" },
    { value: "action" },
  ];
  get rightHeaders() {
    return this.headers.slice(3, this.headers.length - 1);
  }
  isAll(item: ISettingItem) {
    return this.rightHeaders.every((rightHeader) =>
      item.right.includes(rightHeader.value)
    );
  }

  toggleRight(item: ISettingItem, value: string) {
    const valueIndex = item.right.indexOf(value);
    if (valueIndex >= 0) {
      item.right.splice(valueIndex, 1);
    } else {
      item.right.push(value);
    }
  }

  toggleAllRight(item: ISettingItem) {
    if (this.isAll(item)) {
      item.right = [];
    } else {
      item.right = this.rightHeaders.map((rightHeader) => rightHeader.value);
    }
  }

  // action
  openSelectUser() {
    this.step = 1;
    this.dialogTitle = "User";
    this.checkedItems = this.propSettingInfo.items.map((item) => {
      return {
        id: item.id as string,
        department: item.department,
        userName: item.userName,
      };
    });
    this.openDialog();
  }
  openDelete(item: ISettingItem) {
    this.step = 2;
    this.dialogTitle = "Delete";
    this.selectedItem = item;
    this.openDialog();
  }

  deleteItem(settingItem: ISettingItem) {
    const index = this.propSettingInfo.items.findIndex(
      (item) => item.id === settingItem.id
    );
    if (index >= 0) {
      this.propSettingInfo.items.splice(index, 1);
    }
  }
  save() {
    if (this.step === 1) {
      if (this.checkedItems.length) {
        this.propSettingInfo.items = this.checkedItems.map((checkedItem) => {
          const settingItem = this.propSettingInfo.items.find((item) => {
            return item.id === checkedItem.id;
          });
          const newSettingItem: ISettingItem = {
            id: checkedItem.id,
            department: checkedItem.department,
            userName: checkedItem.userName,
            right: [],
          };
          if (!settingItem) {
            newSettingItem.right = this.rightHeaders.map(
              (header) => header.value
            );
            return newSettingItem;
          } else {
            newSettingItem.right = settingItem.right;
            return newSettingItem;
          }
        });
      } else {
        this.propSettingInfo.items = [];
      }
    } else if (this.step === 2 && this.selectedItem) {
      this.deleteItem(this.selectedItem);
      this.selectedItem = null;
    }
    this.closeDialog();
  }

  async validateFormData() {
    const valid: boolean = await this.$validator.validate();
    if (valid) {
      return this.getFormData();
    } else {
      return false;
    }
  }

  getFormData(): ISetting {
    return JSON.parse(JSON.stringify(this.propSettingInfo));
  }
}
</script>
<style lang="scss" scoped>
@import "@/components/Customer/Dialog/Setting/Setting.scss";
</style>
